<?php

namespace app\shopapi\controller;


use app\api\model\ExtendConsume;
use app\api\model\shop\ShopFans;
use app\api\model\UserConsumeLog;
use app\common\controller\Shopapi;
use app\common\library\Ems;
use app\common\library\Sms;
use app\shopapi\model\ExtendConsumeShop;
use app\shopapi\model\MoneyLog;
use app\shopapi\model\ShopUser;
use fast\Random;
use think\Config;
use think\Validate;

/**
 * 会员接口
 */
class User extends Shopapi
{
    protected $noNeedLogin = ['login', 'mobilelogin','wechatlogin','userlist'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->shopauth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->shopauth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->shopauth->getError());
        }
    }

    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->shopauth->nickname]);
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->shopauth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (ShopUser::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }


    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        $code = $this->request->post('code');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }

        $user = ShopUser::get(['mobile'=>$mobile]);
        if ($user) {

            //如果已经有账号则直接登录
            $ret = $this->shopauth->direct($user->id,$code);
        } else {
            $ret = $this->shopauth->register($mobile, Random::alnum(), $mobile, [],$code);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->shopauth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->shopauth->getError());
        }
    }

    /**
     * Notes:微信登录
     * User: gai
     * Date: 2022/12/26
     * Time: 10:40
     */
    public function wechatlogin(){
        $params = input();

        $ret = $this->shopauth->wechat_login($params);
        if ($ret) {
            $info = $this->shopauth->getUserinfo();
            $data = ['userinfo' =>$info ];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->shopauth->getError());
        }
    }

    //进入店铺
    public function enter()
    {
        $shop_id = input('shop_id',0);
        $user = ShopUser::get($this->shopauth->id);
        $user->shop_id = $shop_id;
        $user->save();
        //dump($this->shop_id);die;
        //$ret = $this->setShopid($shop_id);
        $this->success('');
    }

    //粉丝列表
    public function fanslist()
    {
        $param = input();
        $param['shop_id'] = $this->shopauth->shop_id;
        $fans_model = new \app\shopapi\model\ShopFans();

        $lists = $fans_model->lists($param);

        $this->success('',$lists);
    }

    //我的钱包
    public function wallet()
    {
        $shop = \app\api\model\shop\Shop::get($this->shopauth->shop_id);

        $promotion_where = ['ucl.is_to_account'=>0,'ucl.is_refund'=>0,'a.shop_id'=>$this->shopauth->shop_id];

        $promotion_stay_account = ExtendConsumeShop::alias('a')
            ->join('user_consume_log ucl','a.consume_log_id = ucl.consume_id')
            ->where($promotion_where)
            ->sum('a.commission');

        $total_money = MoneyLog::where(['shop_id'=>$this->shopauth->shop_id,'type'=>1])->sum('money');

        //店铺粉丝
        $fans_count = \app\shopapi\model\ShopFans::where('shop_id',$this->shopauth->shop_id)->count();

        $today_income = ExtendConsumeShop::alias('a')
            ->join('user_consume_log ucl','a.consume_log_id = ucl.consume_id')
            ->where(['a.shop_id'=>$this->shopauth->shop_id,'ucl.is_refund'=>0])
            ->whereTime('a.createtime', 'today')
            ->sum('a.commission');

        $total_income = ExtendConsumeShop::alias('a')
            ->join('user_consume_log ucl','a.consume_log_id = ucl.consume_id')
            ->where(['a.shop_id'=>$this->shopauth->shop_id,'ucl.is_refund'=>0])
            ->sum('a.commission');

        $data = [
            'money'=>$shop?$shop['money']:0,//待提现
            'wait_commission'=>$promotion_stay_account,//待到账
            'total_money'=>$total_money,//累计到账
            'fans_count'=>$fans_count,//粉丝数
            'today_income'=>$today_income,//今日收益
            'total_income'=>$total_income,//累计收益
        ];
        $this->success('',$data);
    }


    //推广达人
    public function superior()
    {
        $shop_user = ShopUser::get($this->shopauth->id);

        $parent = \app\admin\model\User::where('id',$shop_user->recommender_id)
            ->field('id,level,nickname,avatar,mobile')->find();
        //dump($shop_user);die;
        $top_parent = UserConsumeLog::getIds($parent->id,3);
        $data = [
            'parent'=>$parent,
            'top_parent'=>$top_parent
        ];

        $this->success('',$data);
    }

    //用户列表
    public function userlist()
    {
        $list = \app\admin\model\shop\User::order('createtime desc')
            ->field('id,nickname,mobile')->select();
        $this->success('',$list);
    }
}